package com.hzeport.bgs22emduty.config.login;



//import com.baomidou.mybatisplus.generator.config.IFileCreate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzeport.bgs22emduty.config.ProfileNotEqual;
import com.hzeport.bgs22emduty.config.interptor.ServletAttributes;
import com.hzeport.bgs22emduty.dto.CustomCodeListDTO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.entity.PersonCurrentCustom;
import com.hzeport.bgs22emduty.entity.SystemModule;
import com.hzeport.bgs22emduty.outbound.BaseDeptInfoRepository;
import com.hzeport.bgs22emduty.outbound.BasePersonInfoRepository;
import com.hzeport.bgs22emduty.outbound.PersonCurrentCustomRepository;
import com.hzeport.bgs22emduty.outbound.SystemModuleRepository;
import com.hzeport.bgs22emduty.util.GuavacacheUtils;
import com.hzeport.bgs22emduty.vo.SystemModule.SystemModuleVO;
import com.hzeport.bgs22emduty.auth.adapter.UserService;
import com.hzeport.bgs22emduty.auth.dto.Function;
import com.hzeport.bgs22emduty.auth.dto.Role;
import com.hzeport.bgs22emduty.auth.h4a.constant.H4AEnum;
        import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
@ProfileNotEqual("bgs22emduty")
public class LoginCompoent implements LoginCompoentService{

    @Autowired
    private UserService userService;
    @Resource
    private SystemModuleRepository systemModuleRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private GuavacacheUtils guavacacheUtils;
    @Resource
    private PersonCurrentCustomRepository personCurrentCustomRepository;



    public UserInfoDetailVO getUserInfo(){
//        UserInfoDetailVO userInfoDetailVO = new UserInfoDetailVO();
        //        UserInfoDetailVO userInfoDetailVO = new UserInfoDetailVO();
        try {
            String ticket = ServletAttributes.getRequest().getHeader(H4AEnum.HEAD_TICKET.getValue());
            log.info("ticket");
            UserInfoDetailVO userInfoDetailVO = guavacacheUtils.getUserInfoGuava(ticket);
            log.info("ticket获取到的用户信息："+ JSON.toJSONString(userInfoDetailVO));
            if (userInfoDetailVO != null && userInfoDetailVO.getUserId() != null) {
                PersonCurrentCustom personCurrentCustom = personCurrentCustomRepository.getOne(new LambdaQueryWrapper<PersonCurrentCustom>()
                        .eq(PersonCurrentCustom::getUserNo, userInfoDetailVO.getUserId()), false);
                if (personCurrentCustom != null) {
                    userInfoDetailVO = JSONObject.parseObject(personCurrentCustom.getUserInfoJson(), UserInfoDetailVO.class);
                }
            }

            List<Role> roles = userService.getRoles(ticket);
            userInfoDetailVO.setRole(roles.stream().map(Role::getCode_name).collect(Collectors.toList()));
            log.info("最终返回的用户信息："+ JSON.toJSONString(userInfoDetailVO));
            return userInfoDetailVO;
        }
        catch (Exception ex)
        {
            log.error("获取用户信息出错:"+ex.getMessage());
            return new UserInfoDetailVO();
        }
//        return new UserInfoDetailVO().setUserId("3538350").setUserName("张飞").setCustomscode("bba02f17-b961-4f89-9b87-b2fbb0067268").setPersonId("2981990").setRole(Arrays.asList("123")).setCustomsName("广东分署");
//        //todo 测试数据，发布时清理
    }



    @Override
    public Object systemModule() {
        //菜单树集合
        List<SystemModuleVO> systemModuleVOList = new ArrayList<>();
//        全部菜单
        List<SystemModule> moduleList = systemModuleRepository.list();
        //在全部菜单中找到每个人对应功能点菜单
//        List<SystemModule> moduleList=new ArrayList<>();
//        for (String functionCode : functionCodes) {
//            moduleList=List.stream().filter(i -> i.getFauthorityid().equals(functionCode)).collect(Collectors.toList());
//        }
        //菜单排序
        List<SystemModule> moduleLists=moduleList.stream().sorted(Comparator.comparing(SystemModule::getForderindex)).collect(Collectors.toList());
        //        找到一级菜单
        for (SystemModule systemModule : moduleLists) {
            if(systemModule.getMLevel()==1){
                //根据一级菜单找到二级
                List<SystemModuleVO> Children=new ArrayList<>();  //二级菜单集合
                getChild(systemModule,Children,moduleList);//递归找到二级菜单
                //二级菜单排序
                List<SystemModuleVO> Childrens=Children.stream().sorted(Comparator.comparing(SystemModuleVO::getForderindex)).collect(Collectors.toList());
                SystemModuleVO systemModuleVO = new SystemModuleVO();//菜单树对象
                systemModuleVO.setId(systemModule.getId());
                systemModuleVO.setLabel(systemModule.getFmainalias());
                systemModuleVO.setPath(systemModule.getWPath());
                systemModuleVO.setChildren(Childrens);
                //添加到集合
                systemModuleVOList.add(systemModuleVO);
            }
        }
        //菜单树为空
        if(CollectionUtils.isEmpty(systemModuleVOList)){
            //todo  指定菜单

        }
        return systemModuleVOList;
    }

    @Override
    public List<CustomCodeListDTO> getCustomCodes() {
        String ticket= ServletAttributes.getRequest().getHeader(H4AEnum.HEAD_TICKET.getValue());
        List<Function> functions = userService.getFunctions(ticket);
        List<String> functionStrings=functions.stream().map(Function::getCode_name)
                .collect(Collectors.toUnmodifiableList());
        List<String> customCodes=new ArrayList<>();
        for (String functionString:functionStrings){
            log.info("0|"+functionString);
            if (functionString.contains("DATA_CUS_")) {
                log.info("1|"+functionString);
                String cusString = functionString.replace("DATA_CUS_", "").replaceAll("_", "-").toLowerCase();
                customCodes.add(cusString);
            }
        }
        if(CollectionUtils.isEmpty(customCodes)){
            return new ArrayList<>();
        }else {
            List<CustomCodeListDTO> customCodeListDTOS=customCodes.stream().map(i->{
                CustomCodeListDTO customCodeListDTO=new CustomCodeListDTO();
                customCodeListDTO.setCustomCode(i);
                BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(i);
                customCodeListDTO.setCustomName(baseDeptInfo!=null?baseDeptInfo.getDeptName():"");
                return customCodeListDTO;
            }).collect(Collectors.toList());
            return customCodeListDTOS;
        }
    }

    @Override
    public String setCustom(String customCode ) {
        String ticket= ServletAttributes.getRequest().getHeader(H4AEnum.HEAD_TICKET.getValue());
        guavacacheUtils.setCustom(ticket,customCode);
        return "设置成功";
    }

    private void  getChild(SystemModule systemModule, List<SystemModuleVO> Children , List<SystemModule> moduleList ){
        List<SystemModule> myChildren=moduleList.stream().filter(i->i.getFsuperid()!=null&&i.getFsuperid().toString().equals(systemModule.getId())).collect(Collectors.toList());
        List<SystemModuleVO> myChildrenVO=new ArrayList<>();
        for (SystemModule myChild : myChildren) {
            SystemModuleVO systemModuleVO = new SystemModuleVO();
            systemModuleVO.setId(myChild.getId());
            systemModuleVO.setLabel(myChild.getFmainalias());
            systemModuleVO.setPath(myChild.getWPath());
            systemModuleVO.setForderindex(myChild.getForderindex());
            myChildrenVO.add(systemModuleVO);
        }
        if (!CollectionUtils.isEmpty(myChildren)){
            Children.addAll(myChildrenVO);
            for (SystemModule child:myChildren){
                getChild(child,Children,moduleList);
            }
        }else {
            return ;
        }
    }
}


//    public static void main(String[] args) {
//        String s="DATA_CUS_0CO37A4D_BF06_4107_B9B8_F73649C742E1";
//        List<String> functionStrings= Arrays.asList(s);
//        for (String functionString:functionStrings){
//            if (functionString.contains("DATA_CUS_")) {
//                String cusString = functionString.replace("DATA_CUS_", "").replaceAll("_", "-").toLowerCase();
//                System.out.println(cusString);
//            }
//        }
//    }


